/*******************************************************************************
 *    系统名称   : 约汗乐动力接口/后台管理系统
 *    客户             : 约汗乐动力
 *    文件名        ： LiveAccess.java
 *              (C) Copyright 博智乐创 Corporation 2015
 *               All Rights Reserved.
 *              http://www.bozlc.com
 * *****************************************************************************
 *    注意： 本内容仅限于约汗乐动力软件公司内部使用，未经许可禁止转发
 ******************************************************************************/
package com.xiake.utils;

// TODO: Auto-generated Javadoc
/**
 * Live access object holds only one element, it can
 * record the create time of the element. If current
 * time of touching the element is far away from the
 * create time, then the element expires, and result
 * null.
 *
 * @param <E> the element type
 */
public class LiveAccess<E> {

	/** The ttl in millis. */
	private final int ttlInMillis;
	
	/** The element. */
	private final E element;
	
	/** The create time. */
	private final long createTime;
	
	/**
	 * Instantiates a new live access.
	 *
	 * @param ttlInMillis the ttl in millis
	 * @param element the element
	 */
	public LiveAccess(int ttlInMillis, E element) {
		this.ttlInMillis = ttlInMillis;
		this.element = element;
		this.createTime = System.currentTimeMillis();
	}
	
	/**
	 * Gets the element.
	 *
	 * @return the element
	 */
	public E getElement() {
		long currentTime = System.currentTimeMillis();
		if(ttlInMillis > 0 && currentTime - createTime > ttlInMillis) {
			return null;
		} else {
			return element;
		}
	}
	
	/**
	 * Gets the element if necessary.
	 *
	 * @return the element if necessary
	 */
	public E getElementIfNecessary() {
		return element;
	}

}
